<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>编辑转换自采购订单的入库单(编辑入库单)</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //你要引用的订单类型
        var warehousingEntryId = Ext.create('Ext.form.field.Hidden', {
          name: 'id',
          value:<%=params[:id]%>
        });

        var version = Ext.create('Ext.form.field.Hidden', {
          name: 'lock_version'
        });
        
        var purchaseOrderId = Ext.create('Ext.form.field.Hidden', {
          name: 'purchase_order_id'
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '90%'
        });

        //所有供应商
        var fromVendor = Ext.create('Ext.form.field.Text', {
          fieldLabel: '供应商',
          name: 'vendor_name',
          anchor: '90%',
          readOnly:true
        });
        
        //选供应商ID
        var vendorId = Ext.create('Ext.form.field.Hidden', {
          name: 'vendor_id'
        });
        
        //所有仓库

        var toWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'warehouse_id',
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          minChars: 0,
          editable:false
        });

        //入库日期
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '入库日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "入库日期必须选择",
          emptyText: '请选择日期...'
          //anchor: '50%'
        });
        //-------------------------------------------------------------------------
        //销售订单单号combobox
        var saleOrderNumberCBB = Ext.create('Ext.form.ComboBox', {
          store: saleOrderNumbersForSomeOnePurchaseStore,
          fieldLabel: '销售订单单号',
          allowBlank: false,
          blankText: "销售订单必须选择",
          emptyText: '请选择...',
          displayField: 'order_number',
          hideTrigger:false,          
          loadingText: '搜索中...',
          anchor: '90%',
          minChars: 0
        });

        saleOrderNumberCBB.on('select', function(combo, record, index) {
          var purchaseDetailItemRecord = purchaseDetailsSM.getSelected();
          if (!purchaseDetailItemRecord) {
            return false;
          }

          var oriSaleOrderId = purchaseDetailItemRecord.get('sale_order_id');
          var oriSaleOrderNumber = purchaseDetailItemRecord.get('sale_order_number');
          
          
          //如果重复选择了，就回复原来的值，如果没有就切换到新值上去          
          if (isDuplicateBySaleOrderProduct(entryDetailsDS,records[0].get('sale_order_id'),purchaseDetailItemRecord.get('product_id'))){
            purchaseDetailItemRecord.set('sale_order_id',oriSaleOrderId);
            purchaseDetailItemRecord.set('sale_order_number',oriSaleOrderNumber);
            saleOrderNumberCBB.setValue(oriSaleOrderNumber);
          }else{
            purchaseDetailItemRecord.set('sale_order_id',records[0].get('sale_order_id'));
            purchaseDetailItemRecord.set('sale_order_number',records[0].get('order_number'));
          }
        });

        saleOrderNumberCBB.on('focus', function(combo, record, index) {
          var records = entryDetailsGrid.getSelectionModel().getSelection();
          saleOrderNumberStore.extraParams.purchase_order_id = records[0].get('purchase_order_id');
          saleOrderNumberStore.extraParams.product_id = records[0].get('product_id');
          saleOrderNumberStore.load();          
        });

        Ext.define('EditEntryOrder', {
          extend : 'Ext.data.Model',
          fields : [{name: 'id'},
            {
              name: 'vendor_name',
              mapping: 'vendor.name'
            }, {
              name: 'warehouse_id'
            }, {
              name: 'purchase_order_id'
            }, {
              name: 'action_date',
              type: 'date',
              dateFormat: 'Y/m/d'
            }, {
              name: 'description'
            },{
              name: 'lock_version'
            }
          ]
        });

        Ext.define('EditEntryDetail', {
          extend : 'Ext.data.Model',
          fields : [{name: 'id'},
            {
              name: 'sale_order_number'
            },{
              name: 'purchase_order_id'
            },{
              name: 'sale_order_id'
            },{
              name: 'number'
            },{
              name: 'spec'
            },{
              name: 'product_name'
            },{
              name: 'unit'
            },{
              name: 'quantity',
              type: 'int'
            },{
              name: 'max_quantity',
              mapping:'balance_quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'description'
            },{
              name: 'amount',
              type: 'float'
            }
          ]
        });

        var entryDetailsDS = Ext.create('Ext.data.Store', {
          //autoDestroy : true,
          model : 'EditEntryDetail',
          proxy : {
            type : 'ajax',
            extraParams:{id:warehousingEntryId.getValue()},
            url: '/warehousing_entry/getDetailsBalanceByIdForEdit',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          },
          autoLoad:true
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        //采购订单的产品的Grid
        var entryDetailsGrid = Ext.create('Ext.grid.Panel', {
          store: entryDetailsDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '采购订单Id',
              dataIndex: 'purchase_order_id',
              hidden:true,
              width: 30
            },{
              header: '销售订单ID',
              dataIndex: 'sale_order_id',
              hidden: true,
              width: 50              
            },{
              header: '销售订单单号',
              dataIndex: 'sale_order_number',
              field: saleOrderNumberCBB,
              hidden: true,
              width: 210
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 210
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 115
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              dataIndex: 'quantity',
              align: 'right',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              width: 50
            },{
              header: '备注',
              dataIndex: 'description',
              width: 130,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '90%'
              })
            }],
          selModel : Ext.create('Ext.selection.CheckboxModel'),
          width: 890,
          height: 350,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              disabled: true,
              handler : function(){
                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, entryDetailsGrid.getStore().model);
                entryDetailsDS.insert(0, record);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = entryDetailsGrid.getSelectionModel().getSelection();
                if (!records) {
                  return false;
                }
                cellEditing.cancelEdit();
                entryDetailsDS.remove(records);
              }
            }]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          iconCls: 'icon-save',
          handler: function(){
            //saveWarehousingEntry("save");
            if(entryForPurchaseFormPanel.form.isValid()){              
              var productsJsonStr = gridStoreToJson(entryDetailsDS,rejectKeyArray);
              if (entryDetailsDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = entryForPurchaseFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/warehousing_entry/update',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "编辑入库单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editWarehousingEntryOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editWarehousingEntryOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editWarehousingEntryOrderWin.destroy();
          }
        });
        
        var entryForPurchaseFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '900',
          frame : true,
          url : '/warehousing_entry/update',
          method: 'GET',
          reader: Ext.create('Ext.data.reader.Json',{
            model: 'EditEntryOrder',
            root: 'root'
          }),
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [fromVendor]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toWarehouse]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [entryDetailsGrid]
                }]
            },vendorId,warehousingEntryId,purchaseOrderId,version],
          buttons: [submitButton,closeButton]
        });
        
        entryForPurchaseFormPanel.render('entry_form');

        entryDetailsGrid.on('edit', afterEdit, this );

        function afterEdit(editor,obj,options) {
          // execute an XHR to send/commit data to the server, in callback do (if successful):
          if(obj.field=="quantity"){
            if (obj.record.get('quantity') > obj.record.get('max_quantity') || obj.record.get('quantity')  == 0){
              obj.record.set('quantity', obj.record.get('max_quantity'));
              return;
            }
          }
        }

        warehouseStore.load({callback: function(record, options, success){
            if(success){
              entryForPurchaseFormPanel.form.load({
                url: '/warehousing_entry/getWarehousingEntryById?id=' + <%=params[:id]%>,
                method : 'GET',
                waitMsg: '正在载入数据...',
                success: function(form, action){
                },
                failure: function(form, action){
                  Ext.MessageBox.alert('提示信息', '信息加载失败');
                }
              });
            }else{
              Ext.MessageBox.alert('操作','失败！');
            }
          }});
      })
    </script>
  </head>
  <body>
    <div id="entry_form"></div>
  </body>
</html>
